package com.huangqi.irs;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * irs接口调用测试
 */
public class IrsApiGateway {

    /**
     * 单接口测试
     * @return
     */
    public static String singleTest(String accessKey, String secretKey, String dataApiUrl, String body) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();
        long timestamp = System.currentTimeMillis() / 1000;
        //按照字典对参数进行排序
        Map<String, String> params = new TreeMap<>();
        params.put("access_key", accessKey);
        params.put("timestamp", String.valueOf(timestamp));
        String signString = params.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&"));
        //对参数进行加密
        String signature = org.apache.commons.codec.digest.HmacUtils.hmacSha256Hex(secretKey, signString);
        //获取动态token
        URIBuilder uriBuilder = new URIBuilder("https://drs.sc.yichang.gov.cn/api/apisix/token");
        uriBuilder.addParameter("access_key", accessKey);
        uriBuilder.addParameter("timestamp", String.valueOf(timestamp));
        uriBuilder.addParameter("signature", signature);
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        HttpResponse response = httpClient.execute(httpGet);
        String content = EntityUtils.toString(response.getEntity());
        if(response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(content);
        }
        //解析token返回结果 示例:{"token": "", "expire_time": 0, "error_msg": ""}
        JSONObject jsonObject = JSON.parseObject(content);
        String token = jsonObject.containsKey("token") ? jsonObject.getString("token") : null;
        //token过期时间
        long expireTime = jsonObject.containsKey("expire_time") ? jsonObject.getLong("expire_time") : 0L;
        String errorMsg = jsonObject.containsKey("error_msg") ? jsonObject.getString("error_msg") : null;
        if (errorMsg != null && errorMsg.length() != 0) {
            throw new RuntimeException(errorMsg);
        }
        //进行接口调用
        RequestBuilder requestBuilder = RequestBuilder.create("POST")
                .addHeader("X-ACCESS-TOKEN", token)
                .setUri(new URIBuilder(dataApiUrl).build())
                .setEntity(new StringEntity(body, "utf-8"));
        HttpUriRequest request =requestBuilder.build();
        response = httpClient.execute(request);
        content = EntityUtils.toString(response.getEntity());
        return content;
    }


}
